import React, { useState, useEffect, useRef } from 'react'
import {
    Table,
    Button,
    Modal,
    message
} from 'antd'
import {
    DeleteOutlined,
    UnorderedListOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons'
import { getAllDepartment } from '../../../utils/request/get'
import { addDepartment } from '../../../utils/request/post'
import { updateDepartment } from '../../../utils/request/put'
import { deleteDepartmentById } from '../../../utils/request/delete'
import BasicForm from '../../../components/BasicForm'

const { confirm } = Modal

export default function DepartmentList() {
    const componentName = '部门'
    const [dataSource, setDataSource] = useState([])
    const [currentId, setCurrentId] = useState(-1)
    const [isModalVisible, setIsModalVisible] = useState(false)
    const [isAddVisible, setIsAddVisible] = useState(false)
    const addForm = useRef(null)
    const updateForm = useRef(null)

    useEffect(() => {
        async function fetchData() {
            const res = await getAllDepartment()
            setDataSource(res.data.departments)
        }
        fetchData()
    }, [])

    const deleteData = (item) => {
        setDataSource(dataSource.filter(data => data.id !== item.id));
        deleteDepartmentById(item.id)
    }

    const showConfirm = (type, item) => {
        let obj = {
            icon: <ExclamationCircleOutlined />,
        }
        switch (type) {
            case 'CANCEL':
                obj.title = '您确定要取消吗?'
                obj.onOk = function () { }
                obj.onCancel = function () { console.log('Cancel'); }
                break
            case 'DELETE':
                obj.title = '您确定要删除吗?'
                obj.cancelText = '取消'
                obj.okText = '确定'
                obj.onOk = function () { deleteData(item); }
                obj.onCancel = function () { console.log('Cancel'); }
                break
            default: break
        }
        confirm(obj)
    };

    const openModal = (item) => {
        // console.log(item);
        setIsModalVisible(true)
        setCurrentId(item.id)
        // 防止在modal组件加载之前就设置值
        setTimeout(() => {
            updateForm.current.setFieldsValue({ ...item, title: item.departmentName })
        }, 0)
    }

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            render: (id) => {
                return <b>{id}</b>
            }
        },
        {
            title: '部门名称',
            dataIndex: 'departmentName',
        },
        {
            title: '操作',
            render: (record) => {
                return (
                    <div>
                        <Button
                            danger onClick={() => showConfirm("DELETE", record)}
                            shape="circle" icon={<DeleteOutlined />}>
                        </Button>&nbsp;&nbsp;
                        <Button
                            shape="circle"
                            icon={<UnorderedListOutlined />}
                            type="primary"
                            onClick={() => { openModal(record) }}></Button>
                    </div>
                )
            },
        }
    ]

    const handleUpdateOk = async () => {
        updateForm.current.validateFields().then(value => {
            setIsModalVisible(false)
            updateForm.current.resetFields()
            updateDepartment(currentId, value).then(async res => {
                const data = res.data.department
                if (data) {
                    setDataSource(dataSource.map(item => {
                        if (item.id === currentId) {
                            return { ...item, ...value }
                        }
                        return item
                    }))
                    message.success('修改成功')
                } else {
                    message.error('修改失败')
                }
            })
        })
    }

    const addFormMethod = () => {
        addForm.current.validateFields().then(value => {
            setIsAddVisible(false)
            addForm.current.resetFields()

            addDepartment(value).then(async res => {
                const data = res.data.department
                if (data) {
                    setDataSource([...dataSource, { ...data }])
                    message.success('添加成功')
                } else {
                    message.error('添加失败')
                }
            })

        }).catch(err => { showError(err) })
    }

    const showError = (err) => {
        const errors = err.errorFields
        if (errors.length > 0) {
            message.warning(errors[0].errors[0])
        }
    }

    const handleCancel = () => {
        setIsModalVisible(false)
    }

    return (
        <>
            <Button
                type="primary"
                style={{ marginBottom: '5px' }} onClick={() => setIsAddVisible(true)}>添加{componentName}</Button>
            <Table
                bordered
                columns={columns}
                dataSource={dataSource}
                pagination={{ pageSize: 5 }}
                rowKey={(item) => item.id}
            />
            <Modal
                title={`修改${componentName}`}
                cancelText="取消"
                okText="确定"
                open={isModalVisible}
                onOk={handleUpdateOk}
                onCancel={handleCancel}>
                <BasicForm ref={updateForm} isUpdate={true} title={`${componentName}名称`}></BasicForm>
            </Modal>
            <Modal
                className='modal'
                open={isAddVisible}
                title={`添加${componentName}`}
                okText="完成"
                cancelText="取消"
                onCancel={() => setIsAddVisible(false)}
                onOk={() => addFormMethod()}
            >
                <BasicForm ref={addForm} title={`${componentName}名称`}></BasicForm>
            </Modal>
        </>
    )
}